package org.aceor.mddal.atom;

import org.aceor.mddal.atom.adapter.AbstractAtomConnectionAdapter;
import org.aceor.mddal.atom.adapter.AbstractAtomStatementAdapter;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by lxue on 16/3/27.
 */
public class AtomConnectionWrapper extends AbstractAtomConnectionAdapter implements Connection {

    private static final Logger logger = LoggerFactory.getLogger(AtomConnectionWrapper.class);

    public AtomConnectionWrapper(Connection connection, DataSource atomDataSourceWrapper) {
        super(connection, atomDataSourceWrapper);
    }

    @Override
    public Statement createStatement() throws SQLException {
        AtomStatementWrapper atomStatementWrapper = new AtomStatementWrapper(targetConnection.createStatement(), this);
        statementSet.add(atomStatementWrapper);
        return atomStatementWrapper;
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        AtomPreparedStatementWrapper atomPreparedStatementWrapper = new AtomPreparedStatementWrapper(targetConnection.prepareStatement(sql), this, sql);
        statementSet.add(atomPreparedStatementWrapper);
        return atomPreparedStatementWrapper;
    }


    @Override
    public boolean getAutoCommit() throws SQLException {
        return targetConnection.getAutoCommit();
    }
    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        targetConnection.setAutoCommit(autoCommit);
    }
    @Override
    public void commit() throws SQLException {
        targetConnection.commit();
    }

    @Override
    public void rollback() throws SQLException {
        targetConnection.rollback();
    }

    @Override
    public void close() throws SQLException {
        targetConnection.close();
        if (CollectionUtils.isNotEmpty(statementSet)) {
            for (Statement statement : statementSet) {
                ((AbstractAtomStatementAdapter)statement).close(false);
            }
        }
    }

    @Override
    public boolean isClosed() throws SQLException {
        return targetConnection.isClosed();
    }

    public void removeOpenedStatements(Statement statement) {
        if (!statementSet.remove(statement)) {
            logger.warn("current statmenet ：" + statement + " doesn't exist!");
        }
    }

}
